package yxy.cherry.game.base.mq;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

public class MqManager {
	private static MqManager instance = new MqManager();

	public static MqManager getInstance() {
		return instance;
	}

	private MqManager() {
	}

	private DefaultMQProducer producer;
	private String topic;

	public void init(MqConfig mqConfig) throws MQClientException {
		producer = new DefaultMQProducer(mqConfig.ProducerGroup);
		producer.setNamesrvAddr(mqConfig.NamesrvAddr);
		producer.setInstanceName(mqConfig.InstanceName);
		producer.start();

		this.topic = mqConfig.Topic;
	}

	public void send(String tag, byte[] body) {
		try {
			Message msg = new Message(topic, // topic 主题名称
					tag, // tag 临时值
					body// body 内容
			);
			// MQ异步发送 默认设置
			producer.send(msg, new SendCallback() {

				@Override
				public void onSuccess(SendResult sendResult) {
//					System.out.println(sendResult.toString());
				}

				@Override
				public void onException(Throwable e) {
//					System.out.println(e.toString());
				}
			});

		} catch (Exception e) {
//			e.printStackTrace();
		}
	}

	public void shutdown() {
		producer.shutdown();
	}
}
